﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;

namespace Kanban.Common
{
    public class StringHelper
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5(string str)
        {
            string hashPasswordForStoringInConfigFile = FormsAuthentication.HashPasswordForStoringInConfigFile(str, "MD5");
            return hashPasswordForStoringInConfigFile != null ? hashPasswordForStoringInConfigFile.ToUpper() : "";
        }

        public static ExcelWorksheet ToExcel<T>(List<T> list, Dictionary<string, string> keyValues)
        {
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("sheet");
                int column = 1;//列
                foreach (string key in keyValues.Keys)
                {
                    worksheet.Cells[1, column].Value = key;
                    column++;
                }

                int row = 2;//行
                foreach (var date in list)
                {
                    column = 1;
                    //反射获取数据属性
                    PropertyInfo[] pi = date.GetType().GetProperties();
                    foreach (var value in keyValues.Values)
                    {
                        var info = pi.Where(e => e.Name == value).FirstOrDefault();
                        if (null != info)
                        {
                            worksheet.Cells[row, column].Value = info.GetValue(date);
                        }
                        else
                        {
                            worksheet.Cells[row, column].Value = "";
                        }
                        column++;
                    }
                    row++;
                }
                return worksheet;
            }
        }
    }
}